<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名称"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>

          <!--
            <bubble-select-local
            v-model="filterData.status"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="[
            { label: '全部', value: '' },
            { label: '上架', value: 1 },
            { label: '下架', value: 0 },
            ]"
            placeholder="请选择分类"
            @change="getAxiosData(true)"
            ></bubble-select-local>
            <bubble-select-local
            v-model="filterData.dramaStatus"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="[
            { label: '全部', value: '' },
            { label: '未上映', value: 1 },
            { label: '更新中', value: 2 },
            { label: '已完结', value: 3 },
            ]"
            placeholder="请选择分类"
            @change="getAxiosData(true)"
            ></bubble-select-local> 
          -->
          <bubble-select-local
            v-model="filterData.categoryId"
            labelKey="categoryName"
            valueKey="categoryId"
            style="width: 100%"
            :param="{ haveAll: true }"
            :axios="dramaCategoryListAxios"
            placeholder="请选择分类"
            @change="getAxiosData(true)"
          ></bubble-select-local>

          <bubble-select-local
              v-model="filterData.wechatPushStatus"
              labelKey="name"
              valueKey="code"
              style="width: 100%"
              :list="weChatStatus"
              placeholder="请选择微信发布状态"
              @change="getAxiosData(true)"
          ></bubble-select-local>



        </div>
        <div class="right-box">
          <el-button type="success" @click="handlerDramaReal">短剧变现</el-button>

          <el-button type="success" :icon="IconShare" @click="handlerDramaAuth">短剧授权</el-button>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>

      <el-table-column
          fixed
          type="index"
          label="#"
          sortable
          width="60"
          align="center"
          headerAlign="center"
      >
        <template #default="scope">
          <el-checkbox v-model="scope.row.isCheck" true-value="1" false-value="0"></el-checkbox>
        </template>

      </el-table-column>


      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column fixed label="海报" prop="dramaTitle" minWidth="72">
        <template #default="{ row }">
          <base-image
            style="width: 45px; height: 80px; border-radius: 4px"
            :src="row.dramaCover"
            previewTeleported
            :previewSrcList="[row.dramaCover!]"
          ></base-image>
        </template>
      </el-table-column>
      <el-table-column fixed label="短剧名称" prop="dramaTitle" minWidth="180"></el-table-column>
      <el-table-column label="短剧ID" prop="dramaId" minWidth="140"></el-table-column>
      <el-table-column label="上映状态" minWidth="90">
        <template #default="{ row }">
          <el-tag :type="row.dramaStatus === 3 ? 'success' : row.dramaStatus === 2 ? 'primary' : 'info'" size="small">{{ row.dramaStatusDesc }}</el-tag>
        </template>
      </el-table-column>
      <!--
        <el-table-column label="整剧免费" minWidth="90">
        <template #default="{ row }">
        <el-tag v-if="row.isFree === 1" key="el-tag-1" type="success" size="small">是</el-tag>
        <el-tag v-else key="el-tag-2" type="danger" size="small">否</el-tag>
        </template>
        </el-table-column> 
      -->
      <el-table-column label="抖音发布状态" minWidth="110">
        <template #default="{ row }">
          <el-tag :type="statusMapList[row.dyPushStatus as PlatformUploadStatus]?.type || 'danger'" size="small">
            {{ statusMapList[row.dyPushStatus as PlatformUploadStatus]?.upLabel || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="快手发布状态" minWidth="110">
        <template #default="{ row }">
          <el-tag :type="statusMapList[row.ksPushStatus as PlatformUploadStatus]?.type || 'danger'" size="small">
            {{ statusMapList[row.ksPushStatus as PlatformUploadStatus]?.upLabel || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="微信发布状态" minWidth="110">
        <template #default="{ row }">
          <el-tag :type="statusMapList[row.wechatPushStatus as PlatformUploadStatus]?.type || 'danger'" size="small">
            {{ statusMapList[row.wechatPushStatus as PlatformUploadStatus]!.upLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <!--
        <el-table-column label="推荐状态" minWidth="90">
        <template #default="{ row }">
        <el-tag v-if="row.isRecommend === 1" key="el-tag-1" type="success" size="small">已推荐</el-tag>
        <el-tag v-else key="el-tag-2" type="danger" size="small">未推荐</el-tag>
        </template>
        </el-table-column> 
      -->
      <el-table-column label="总集数" prop="seqNum" minWidth="90"></el-table-column>
      <!--
        <el-table-column label="分享解锁集数" prop="shareUnlockNum" width="120"></el-table-column>
        <el-table-column label="免费集数" prop="freeEpisodeNum" minWidth="90"></el-table-column>
        <el-table-column label="单集价格" prop="price" sortable minWidth="110"></el-table-column>
        <el-table-column label="单集K币" prop="virtualCoin" sortable minWidth="110"></el-table-column>
        <el-table-column label="全集价格" prop="allEpisodePrice" sortable minWidth="110"></el-table-column>
        <el-table-column label="全集K币" prop="allEpisodeVirtualCoin" sortable minWidth="110"></el-table-column>
        <el-table-column label="分类" prop="dramaCategoryName" minWidth="120"></el-table-column>
        <el-table-column label="导演" prop="director" minWidth="90"></el-table-column>
        <el-table-column label="演员" prop="performer" minWidth="90"></el-table-column>
        <el-table-column label="标签" prop="tags" minWidth="120"></el-table-column> 
      -->
      <el-table-column fixed="right" label="操作" width="130" align="center" headerAlign="center">
        <template #default="{ row }">
          <div style="display: flex; flex-direction: column; justify-content: space-around; height: 80px; overflow: hidden">
            <el-button
              link
              :type="[0, null].includes(row.dyPushStatus) ? 'success' : 'primary'"
              size="small"
              style="margin-left: 0"
              :icon="RiTiktokLine"
              :loading="row._publishDyLoading"
              @click="handlePublishToThirdPartyPlatforms(row, 1)"
            >
              {{ [0, null].includes(row.dyPushStatus) ? '发布至抖音' : '抖音发布详情' }}
            </el-button>
            <el-button
              link
              :type="[0, null].includes(row.ksPushStatus) ? 'success' : 'primary'"
              size="small"
              style="margin-left: 0"
              :icon="SimpleIconsKuaishou"
              :loading="row._publishKsLoading"
              @click="handlePublishToThirdPartyPlatforms(row, 2)"
            >
              {{ [0, null].includes(row.ksPushStatus) ? '发布至快手' : '快手发布详情' }}
            </el-button>
            <el-button
              link
              :type="[0, null].includes(row.wechatPushStatus) ? 'success' : 'primary'"
              size="small"
              style="margin-left: 0"
              :icon="TdesignLogoWechatStroke"
              :loading="row._publishWxLoading"
              @click="handlePublishToThirdPartyPlatforms(row, 3)"
            >
              {{ [0, null].includes(row.wechatPushStatus) ? '发布至微信' : '微信发布详情' }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <release-details ref="releaseDetailsRef"></release-details>
    <drama-authorization ref="dramaAuthorizationRef"></drama-authorization>
    <drama-realization
        :list="tableData.filter(item=>{
      return item.isCheck
    })"
        ref="dramaRealizationRef"></drama-realization>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconShare from '~icons/ep/share';
  import IconSearch from '~icons/ep/search';
  import RiTiktokLine from '~icons/ri/tiktok-line';
  import SimpleIconsKuaishou from '~icons/simple-icons/kuaishou';
  import TdesignLogoWechatStroke from '~icons/tdesign/logo-wechat-stroke';
  import {
    type DamaListRequest,
    type DramaItem,
    type PushPlatform,
    dramaCategoryListAxios,
    getDamaListAxios,
    publishToThirdPartyPlatforms,
  } from '@/api/drama-management';
  import ReleaseDetails from './components/release-details.vue';
  import DramaAuthorization from './components/drama-authorization.vue';
  import DramaRealization from './components/drama-realization.vue';
  import { type PlatformUploadStatus, statusMapList } from './publish-util';

  type _DramaItem = DramaItem & {
    /** 修改抖音推送的加载状态 */
    _publishDyLoading?: boolean;
    /** 修改快手推送的加载状态 */
    _publishKsLoading?: boolean;
    /** 修改微信推送的加载状态 */
    _publishWxLoading?: boolean;

    dyPushStatus: 0 | 1 | 2 | 3 | 4;
  };
  onMounted(() => {
    getAxiosData();
  });

  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const releaseDetailsRef: $RefComp<typeof ReleaseDetails> = ref(null);
  const dramaAuthorizationRef: $RefComp<typeof DramaAuthorization> = ref(null);
  const dramaRealizationRef: $RefComp<typeof DramaRealization> = ref(null);

  const weChatStatus=ref(((map)=>{
    let arr = [];
    for(let i in map){
      arr.push({
        code:i,
        name:map[i].upLabel
      })
    }

    return arr;
  })(statusMapList.value))

  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const filterData: Ref<DamaListRequest> = ref<DamaListRequest>({
    dramaTitle: '',
    categoryId: '',
    status: '',
    dramaStatus: '',
    current: 1,
    size: 40,
  });

  const tableData = ref<_DramaItem[]>([]);
  const description = ref('');
  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getDamaListAxios(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /** 发布至第三方平台 */
  async function handlePublishToThirdPartyPlatforms(row: _DramaItem, platform: PushPlatform) {
    // 发布详情
    if (platform === 1 && ![0, null].includes(row.dyPushStatus!)) {
      handlePublishDetails(row, platform);
      return;
    }
    if (platform === 2 && ![0, null].includes(row.ksPushStatus!)) {
      handlePublishDetails(row, platform);
      return;
    }
    if (platform === 3 && ![0, null].includes(row.wechatPushStatus!)) {
      handlePublishDetails(row, platform);
      return;
    }
    await ElMessageBox.confirm('确认发布', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    });
    try {
      handlePublishLoading(row, platform, true);
      await publishToThirdPartyPlatforms({
        dramaId: row.dramaId!,
        pushPlatform: platform,
      });
      handlePublishLoading(row, platform, false);
      ElToast.success(`发布成功`);
      getAxiosData(false);
    } catch (error) {
      handlePublishLoading(row, platform, false);
      ElToast.error(error.msg || `发布失败，-BD004`);
    }
  }

  /** 发布详情 */
  function handlePublishDetails(row: _DramaItem, platform: PushPlatform) {
    releaseDetailsRef.value?.show({ dramaId: row.dramaId!, dramaTitle: row.dramaTitle!, platform });
  }

  /** 发布按钮loading处理 */
  function handlePublishLoading(row: _DramaItem, platform: PushPlatform, status: boolean) {
    switch (platform) {
      case 1:
        row._publishDyLoading = status;
        break;
      case 2:
        row._publishKsLoading = status;
        break;
      case 3:
        row._publishWxLoading = status;
        break;
      default:
        break;
    }
  }

  /** 短剧授权 */
  function handlerDramaAuth() {
    dramaAuthorizationRef.value?.show();
  }

  function handlerDramaReal() {
    //TODO 选择短剧
    let list =tableData.value.filter(item=>{
      return item.isCheck
    });

    if(list.length>0){
      dramaRealizationRef.value?.show();
    }else{
      ElToast.error(`请选择短剧`);
    }

  }

</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: grid;
      flex: 1;
      grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
      grid-gap: 15px;
      margin-right: 15px;
    }
  }
</style>
